<?php
namespace Manage\Model;
use Think\Model;
use Common\Library\Category;
class NavigationModel extends Model{
	public function operNavigation($data,$navigation_id=0){
		$navigation_data=$this->data($data)->create();
		$navigation_data['date_modified']=time();
		if($navigation_id){		
			$this->where(array('navigation_id'=>$navigation_id))->save($navigation_data);
		}else{
			$navigation_data['date_added']=time();
			$navigation_id=$this->add($navigation_data);
		}
		$NavigationDescriptionModel=M('NavigationDescription');
		$map['navigation_id']=$navigation_id;
		$NavigationDescriptionModel->where($map)->delete();
		foreach ($data['navigation_description'] as $language_id => $navigation_description) {
			$navigation_description['language_id']=$language_id;
			$navigation_description['navigation_id']=$navigation_id;
			$NavigationDescriptionModel->data($navigation_description)->add();
		}
	}
	public function getNavigation($navigation_id){
		$map=array('navigation_id'=>(int)$navigation_id);
		$navigation=$this->where($map)->find();
		$Nd=M('NavigationDescription')->where($map)->select();
		foreach ($Nd as $v) {
			$navigation['navigation_description'][$v['language_id']]=$v;
		}
		
		return $navigation;
	}
	
	public function getNavigations($data){
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		$order='sort_order '. (isset($data['order'])?$data['order']:'ASC');
		$order .= ',navigation_id DESC';
		if(isset($data['status'])) $map['status']=$data['status'];
		if(isset($data['navigation_id'])) $map[C('DB_PREFIX').'navigation.navigation_id']=array('neq',$data['navigation_id']);
		if($data['title']) $map['title'] = array('like',"%".$data['title']."%");

		$navigations=$this->join('LEFT JOIN  __NAVIGATION_DESCRIPTION__ ON __NAVIGATION__.navigation_id=__NAVIGATION_DESCRIPTION__.navigation_id')->where($map)->field(C('DB_PREFIX')."navigation.navigation_id,title,href,parent_id,sort_order,status")->order($order)->select();
		return $navigations;
	}

	public function getChildId($navigation_id){
		$nav=$this->select();
		$nav_ids=Category::getChildsId ($nav, $navigation_id,"navigation_id","parent_id");
		$nav_ids=array_merge(array($navigation_id),$nav_ids);		
		return $nav_ids;
	}

	public function del($navigation_id){
		$return=0;
		$map['navigation_id']=array('in',$this->getChildId($navigation_id));
		M('NavigationDescription')->where($map)->delete();
		$return=$this->where($map)->delete();		
		return $return;
	}
}